// pages/sureorder/sureorder.js
import {
  ajax,
  src,
  util
} from "../../utils/util.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // markers: [{
    //   iconPath: "/pages/images/address.png",
    //   id: 0,
    //   latitude: 23.099994,
    //   longitude: 113.324520,
    //   width: 50,
    //   height: 50
    // }],
    active: 1,
    showcoupon: 0,
    canusecoupon: [],
    CartIDStr: "",
    sureorderlist: "",
    allmoney: 0,
    shownum: 3,
    yixuancoupon: "",
    xiaoji: 0,
    bz: "",
    ordermsg: "",
    ischeck: false,
    currentaddress: "",

    canusenum:0,


    WholeCouponID:"",
    JSCouponID:"",
    allcouponmoney:0,

    showjuli: false,

  },
  tcshowjuli: function () {
    this.setData({
      showjuli: false
    })
  },


  rad: function (d) {
    return d * Math.PI / 180.0;
  },


  // 根据经纬度计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
  getDistance: function (lat1, lng1, lat2, lng2) {

    var radLat1 = this.rad(lat1);
    var radLat2 = this.rad(lat2);
    var a = radLat1 - radLat2;
    var b = this.rad(lng1) - this.rad(lng2);
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
      Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137; // EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000;
    //输出为公里

    var distance = s;
    var distance_str = "";

    if (parseInt(distance) >= 1) {
      distance_str = distance.toFixed(1) + "km";
    } else {
      distance_str = distance * 1000 + "m";
    }

    //s=s.toFixed(4);

    // console.info('lyj 距离是', s);
    // console.info('lyj 距离是', distance_str);
    return s;
  },


  canpeisong: function () {
    var lat1 = this.data.currentaddress.latitude
    var lng1 = this.data.currentaddress.Longitude

    var lat2 = this.data.all.lat
    var lng2 = this.data.all.lng

    var juli = this.getDistance(lat1, lng1, lat2, lng2)
    console.log(juli, "距离啊")

    if (juli > this.data.all.PSDistance) {
      this.setData({
        showjuli: true
      })
      return 0
    } else {
      return 1
    }

  },

  tcshowjuli: function () {
    this.setData({
      showjuli: false
    })
  },


  allmoney:function(){
    var allmoney= this.data.obj.price*this.data.obj.selfnum
    this.setData({
      allmoney: allmoney
    })

    this.getallcoupon()
  },

  xiaoji: function () {
    var allmoney = this.data.allmoney
    // 加运费
    if (this.data.active == 2) {
      allmoney += this.data.all.PSMoney

      // 判断是否免运费
      if (allmoney < this.data.all.MPSMoney) {

      } else {
        allmoney -= this.data.all.PSMoney
      }
    }
    // 减掉已优惠
    allmoney -= this.data.allcouponmoney

    this.setData({
      xiaoji: allmoney
    })

  },


  allcouponmoney: function () {
    var JSCouponID = this.data.JSCouponID
    var WholeCouponID = this.data.WholeCouponID

    var allcouponmoney = 0
    var array = []

    if ((typeof JSCouponID == 'object') && JSCouponID.constructor == Array) {
      for (var x in JSCouponID) {
        array.push(JSCouponID[x])
      }
    } else {
      array.push(JSCouponID)
    }
    array.push(WholeCouponID)
    console.log(array)

    for (var x in this.data.canusecoupon) {
      for (var y in this.data.canusecoupon[x]) {
        if (array.indexOf(this.data.canusecoupon[x][y].ReceiveCouponID) != -1) {
          allcouponmoney += this.data.canusecoupon[x][y].CouponMoney
        }
      }
    }
    this.setData({
      allcouponmoney: allcouponmoney
    })
    this.xiaoji()
  },
  tccoupon:function(){
    this.setData({
      showcoupon: 1
    })
  },


  getallcoupon: function () {
    ajax('/api/CouponCollection/Get?requestContent=' + JSON.stringify({
      token: wx.getStorageSync('Access_token'),

      ActivityIDStr: this.data.all.ID,
      Vtype: 1,
      // PTID: this.data.CartIDStr, 

      PageIndex: 0,
      ProvinceName: wx.getStorageSync('address_component').province,
      CityName: wx.getStorageSync('address_component').city,
      DistrictName: wx.getStorageSync('address_component').district,
      Title: "",
    }), {
        header: {
          'Accept': 'application/x-www-form-urlencoded', // 默认值
        },
        method: "get",
      }, res => {
        console.log(res)



        var wu = []
        var quan = []
        var huodong = []


      
        for (var a in res.Models) {
          res.Models[a].ischeck = false
          res.Models[a].cantuse = false
          if (res.Models[a].CouponType==0){
            wu.push(res.Models[a])
            
          }
          if (res.Models[a].CouponType == 2) {
            quan.push(res.Models[a])
          }
          if (res.Models[a].CouponType == 4) {
            guodong.push(res.Models[a])
          }

          // 判断满减
          if (res.Models[a].ZDMoney <= this.data.allmoney) {
            res.Models[a].cantman = false
            var canusenum = this.data.canusenum += 1
            this.setData({
              canusenum: canusenum
            })
          } else {
            res.Models[a].cantman = true
          }
        } 

        var list=[]
        list.push(wu)
        list.push(quan)
        list.push(huodong)
        // 优惠券类型
        // 0 无门槛(跳转首页)
        // 1指定活动满减(跳转拼购详情)
        // 2全品满减劵(跳转商户)
        // 3指定商品满减劵(跳转商户商品详情)
        // 4活动免费领(暂时无效)
        // 5商品免费领(暂时无效)

        this.setData({
          canusecoupon: list
        })


      })

  },

  getlistalladdress: function (Defaultaddress, siteid) {
    ajax('/api/Myaddress/Get?requestContent=' + JSON.stringify({
      token: wx.getStorageSync('Access_token'),
      Defaultaddress: Defaultaddress
    }), {
        header: {
          'Accept': 'application/x-www-form-urlencoded', // 默认值
        },
        method: "get",
      }, res => {
        console.log(res)
        console.log(siteid)
        if (siteid != "") {
          for (var x in res.Models) {
            if (res.Models[x].ID == siteid) {
              this.setData({
                currentaddress: res.Models[x]
              })
            }
          }
        } else {
          this.setData({
            currentaddress: res.Models[0]
          })
        }
      })
  },
  /*
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var all = JSON.parse(options.all)
    var obj = JSON.parse(options.obj)

    if (obj.isdandu){ 
      if (obj.stylelength==0){
        var price = all.SingleBuyPrice
      }else{
        var price = obj.morenselect.SingleBuyPrice
      }
    }else{
      if (obj.stylelength == 0) {
        var price = all.PTPrice
      } else {
        var price = obj.morenselect.PTPrice
      }
    }

    obj.price = price

    this.setData({
      all: all,
      obj: obj
    })


    this.allmoney()
    // this.getallcoupon()
    this.xiaoji()

    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#000',
    })


    // this.getlistalladdress(0, "")
  },

  lookgengduo: function () {
    if (this.data.shownum == 3) {
      this.setData({
        shownum: 100
      })
    } else {
      this.setData({
        shownum: 3
      })
    }

  },

  toselectaddress: function () {
    if(this.data.showjuli==true){
      this.setData({
        showjuli:false
      })
    }
    wx.navigateTo({
      url: '/pages/selectaddress/selectaddress',
    })
  },
  select: function (e) {
    var index = e.currentTarget.dataset.index
    if (index == 2) {
      if (this.data.all.PSCheckFlag == 0) {
        wx.showToast({
          title: '未开启送货上门',
          icon: 'none',
          duration: 2000
        })
        this.setData({
          active: 1
        })
      } else {
        this.setData({
          active: index
        })
        this.xiaoji()

        if (this.data.siteid) {
          this.getlistalladdress(1, this.data.siteid)
        }
        else {
          this.getlistalladdress(0, "")
        }

      }

    } else {
      this.setData({
        active: index
      })
      this.xiaoji()
    }
  },
  tctc: function () {
    this.allcouponmoney()
    this.setData({
      showcoupon: 0
    })
  },

  clickdanxuans: function (e) {

    var index = e.currentTarget.dataset.index
    var fuindex = e.currentTarget.dataset.fuindex
    console.log(index)
    console.log(fuindex)

    var array = this.data.canusecoupon;

    var weizhi = "canusecoupon[" + fuindex + "]["+index+"]."//这里需要将设置的属性用字符串进行拼接
   
    // 取消选择
    if (array[fuindex][index].ischeck) {
      if(fuindex==0){
        //无
        for (var x in array[fuindex]){
          var weizhi1 = "canusecoupon[" + fuindex + "][" + x + "]."
          this.setData({
            [weizhi1 + "cantuse"]: false,
          })
        }
        this.setData({
          [weizhi +"ischeck"]: !array[fuindex][index].ischeck,
          WholeCouponID: ""
        })
      }else if(fuindex==1){
        //全

        for (var x in array[fuindex]) {
          var weizhi1 = "canusecoupon[" + fuindex + "][" + x + "]."
          this.setData({
            [weizhi1 + "cantuse"]: false,
          })
        }

        for (var x in array[2]) {
          var weizhi1 = "canusecoupon[" + 2 + "][" + x + "]."
          this.setData({
            [weizhi1 + "cantuse"]: false,
          })
        }

        this.setData({
          [weizhi + "ischeck"]: !array[fuindex][index].ischeck,
          JSCouponID: ""
        })
      } else if (fuindex == 2) {
        // huodong
        for (var x in array[fuindex]) {
          var weizhi1 = "canusecoupon[" + fuindex + "][" + x + "]."
          this.setData({
            [weizhi1 + "cantuse"]: false,
          })
        }

        for (var x in array[1]) {
          var weizhi1 = "canusecoupon[" + 1 + "][" + x + "]."
          this.setData({
            [weizhi1 + "cantuse"]: false,
          })
        }
        
        this.setData({
          [weizhi + "ischeck"]: !array[fuindex][index].ischeck,
          JSCouponID: ""
        })
      }
      
    } 
     // 选择
    else if (!array[fuindex][index].ischeck) {
      if (fuindex == 0) {
        //无
        console.log("cantuse")

        for (var x in array[fuindex]) {
          if(x==index){
            this.setData({
              [weizhi + "cantuse"]: false,
              [weizhi + "ischeck"]: !array[fuindex][index].ischeck,
              WholeCouponID: array[fuindex][index].ReceiveCouponID
            })
          }else{
            var weizhi1 = "canusecoupon[" + fuindex + "][" + x + "]."
            this.setData({
              [weizhi1 + "cantuse"]: true,
            })
          }
        }
      } else if (fuindex == 1) {
        //全

        for (var x in array[fuindex]) {
          if (x == index) {
            this.setData({
              [weizhi + "cantuse"]: false,
              [weizhi + "ischeck"]: !array[fuindex][index].ischeck,
              JSCouponID: array[fuindex][index].ReceiveCouponID
            })
          } else {
            var weizhi1 = "canusecoupon[" + fuindex + "][" + x + "]."
            this.setData({
              [weizhi1 + "cantuse"]: true,
            })
          }
        }

        for (var x in array[2]) {
          var weizhi1 = "canusecoupon[" + 2 + "][" + x + "]."
          this.setData({
            [weizhi1 + "cantuse"]: true,
          })
        }
        
      } else if (fuindex == 2) {
        // huodong
        for (var x in array[fuindex]) {
          if (x == index) {
            this.setData({
              [weizhi + "cantuse"]: false,
              [weizhi + "ischeck"]: !array[fuindex][index].ischeck,
              JSCouponID: array[fuindex][index].ReceiveCouponID
            })
          } else {
            var weizhi1 = "canusecoupon[" + fuindex + "][" + x + "]."
            this.setData({
              [weizhi1 + "cantuse"]: true,
            })
          }
        }
        for (var x in array[1]) {
          var weizhi1 = "canusecoupon[" + 1 + "][" + x + "]."
          this.setData({
            [weizhi1 + "cantuse"]: true,
          })
        }
      }
    }
  },

  queren: function () {
    this.allcouponmoney()
    this.setData({
      showcoupon: 0
    })

  },


  topay: function () {
    wx.navigateTo({
      url: '/pages/pay/pay',
    })
  },


  getinputbz: function (e) {
    var bz = event.detail.value
    this.setData({
      bz: bz
    })
  },
  btntijiao: function () {

    var aa = this.canpeisong()
    if (aa == 0) {
      return
    }

    console.log("dddddddd")
    var queue = []
    // for (var x in sureorderlist){
    // }
    var obj = {}
    if (this.data.obj.isdandu){
      obj.VType = 6
    }else{
      obj.VType = 1
    }

    console.log(obj.VType,"6单独")

    obj.ShopID = this.data.all.DealerID
    // ：1：自提2：送货上门
    obj.SHWay = this.data.active
    // 1拼购 2助力免单 3团购 4奖品 5单买 6拼购单买 7发布商品
    obj.UType=this.data.all.MType
    // 用户类型： 0: 智客通 1: 经销商 2: 商户 3: 代理商
    obj.Sponsor=0
    obj.IsFirst=0
    var JSCouponID = this.data.JSCouponID
    var WholeCouponID = this.data.WholeCouponID
    if (WholeCouponID == "") {
      if (JSCouponID == "") {
        obj.ReceiveCouponID = 0
      } else {
        obj.ReceiveCouponID = JSCouponID
      }
    } else {
      if (JSCouponID == "") {
        obj.ReceiveCouponID = WholeCouponID
      } else {
        obj.ReceiveCouponID = WholeCouponID + "," + JSCouponID
      }
    }
    obj.PGID = this.data.all.ID
    obj.OrderNumber=this.data.obj.selfnum
    if(this.data.obj.stylelength==0){
      obj.SKUID = 0
    }else{
      obj.SKUID = this.data.obj.morenselect.ID
    }
    obj.Remark=this.data.bz
   
    if (this.data.active == 1) {
      obj.Orderaddress = this.data.all.Address
      obj.Longitude = this.data.all.lng
      obj.latitude = this.data.all.lat
      obj.PersonAddress = 0
      obj.freight = 0

    } else if (this.data.active == 2) {
      obj.Orderaddress = this.data.currentaddress.Locationaddress
      obj.Longitude = this.data.currentaddress.Longitude
      obj.latitude = this.data.currentaddress.latitude
      obj.PersonAddress = this.data.currentaddress.ID
      obj.freight = this.data.PSMoney
    }

    queue.push(obj)
    console.log(queue, 'queue')
    ajax('/api/OrderCareful/OrderInsert?requestContent=' + JSON.stringify({
      token: wx.getStorageSync('Access_token'),
      queue: queue

    }), {
        header: {
          'Accept': 'application/x-www-form-urlencoded', // 默认值
        },
        method: "post",
      }, res => {

        if (res.Message != "") {
          console.log(res.Message)
          var msg=res.Message.split(",")

          this.setData({
            msg: msg
          })
          var OrderType
          if (this.data.obj.isdandu){
            OrderType=6
          }else{
            OrderType = 1
          }
          

          wx.navigateTo({
            url: '/pages/pay/pay?orderid=' + this.data.msg[0] + '&ordercode=' + this.data.msg[1] + '&OrderType=' + OrderType
          })

        } else {
          wx.showToast({
            title: '提交订单失败',
            icon: 'none',
            duration: 2000
          })
        }

      })
  },




  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (wx.getStorageSync("siteid")) {
      var siteid = wx.getStorageSync("siteid")
      console.log(siteid)

      this.setData({
        siteid: siteid
      })

    }

    if (this.data.active == 2) {
      this.getlistalladdress(1, this.data.siteid)
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})